package com.jee.ssm.modules.parkDepot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jee.ssm.common.utils.hik.HikUtils;
import com.jee.ssm.model.ParkDepot;
import com.jee.ssm.model.aipark.AiparkReceive;
import com.jee.ssm.model.hik.HikPage;
import com.jee.ssm.model.hik.receive.LaneInfo;
import com.jee.ssm.model.hik.receive.ParkDepotInfo;
import com.jee.ssm.model.hik.receive.VehicleRecord;
import com.jee.ssm.modules.parkDepot.services.ParkDepotService;
import com.jee.ssm.common.config.AiparkConfig;
import com.jee.ssm.common.log.AdminControllerLog;
import com.jee.ssm.modules.ssm.controller.AdminBaseController;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.common.utils.HttpUtils;
import com.jee.ssm.common.utils.SingUtils;
import com.jee.ssm.common.utils.TimeUtils;
import com.jee.ssm.common.utils.UUIDFactory;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 停车场管理 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/parkDepot")
public class ParkDepotController extends AdminBaseController<ParkDepot> {


    /**
     * 进入停车场添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("parkDepot:add")
    public String add(ModelMap model){

        model.put("longId", UUIDFactory.getStringId());
        return "manager/park-depot/add";
    }

    /**
     * 展示地图
     * @return
     */
    @RequestMapping(value = "/map")
    public String map() {
        return "manager/park-depot/map";
    }

    @RequestMapping(value = "/relate")
    public String relate(ModelMap model, String hikId) {
        model.put("hikId", hikId);
        return "manager/park-depot/relate";
    }

    @RequestMapping(value = "/relateOneSelf")
    @ResponseBody
    public Tip relateOneSelf(ParkDepot parkDepot) {
        Tip tip = new Tip();
        parkDepot.setId(UUIDFactory.getStringId());
        parkDepot.setCreateTime(new Date());
        parkDepot.setUpdateTime(new Date());
        try {
            parkDepotService.relateOneSelf(parkDepot);
        } catch (Exception e) {
            e.printStackTrace();
            tip = new Tip(1, "系统异常，请刷新重试");
        }
        return tip;
    }

    @RequestMapping(value = "/editRelate")
    public String editRelate(ModelMap model, String id) {
        ParkDepot parkDepot = parkDepotService.selectById(id);
        model.put("parkDepot", parkDepot);
        return "manager/park-depot/relate-edit";
    }

    @RequestMapping(value = "/editOneSelf")
    @ResponseBody
    public Tip editOneSelf(ParkDepot parkDepot) {
        Tip tip = new Tip();
        try {
            parkDepot.setUpdateTime(new Date());
            parkDepotService.updateById(parkDepot);
        } catch (Exception e) {
            e.printStackTrace();
            tip = new Tip(1, "系统异常，请刷新重试");
        }
        return tip;
    }

    /**
     * 进入停车场编辑页面
     * @param model 返回停车场的容器
     * @param id 停车场id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("parkDepot:edit")
    public String edit(ModelMap model, @RequestParam String id) {

        model.put("data",parkDepotService.selectById(id));
        return "manager/park-depot/edit";
    }


    /**
     * 停车场添加
     * @param parkDepot 带id的停车场对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("parkDepot:add")
    @AdminControllerLog(description = "添加停车场" )
    public Tip save(ParkDepot parkDepot)  {

        try {
            parkDepot.setCarUsedNum(0);
            parkDepot.setTrunkUsedNum(0);
            parkDepot.setCreateTime(new Date());
            parkDepot.setUpdateTime(new Date());
            parkDepot.setHikId(UUIDFactory.getStringId());
            parkDepotService.insert(parkDepot);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1,"添加失败！");
        }

    }


    /**
     * 根据 id 修改停车场
     * @param parkDepot 带id的停车场对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("parkDepot:edit")
    @AdminControllerLog(description = "修改停车场" )
    public Tip update(ParkDepot parkDepot) {

        try {
            parkDepotService.updateById(parkDepot);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除停车场
     * @param id 停车场id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("parkDepot:delete")
    @AdminControllerLog(description = "删除停车场" )
    public Tip delete(@RequestParam String id) {

        try {
            parkDepotService.deleteById(id);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"删除失败！");
        }

    }


    /**
     * 根据 id 列表批量删除
     * @param ids 停车场id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("parkDepot:delete")
    @AdminControllerLog(description = "批量删除停车场" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {

        try {
            parkDepotService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量删除失败！");
        }

    }


    /**
     * 根据 id 查找停车场
     * @param id 停车场id
     * @return 停车场对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("parkDepot:list")
    public ParkDepot find(@RequestParam String id) {

        return parkDepotService.selectById(id);
    }


    /**
     * 获取停车场列表 获取全部 不分页
     * @param request 请求参数
     * @return 停车场列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("parkDepot:list")
    public String all(HttpServletRequest request,ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取停车场列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 停车场列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("parkDepot:list")
    public String list(HttpServletRequest request, ModelMap modelMap, Integer page, Integer size) {
        List<ParkDepotInfo> list = null;
        Tip tip = HikUtils.getParkingPage(page, size);
        Integer total = 0;
    	if(tip.getSuccess()) {
    		HikPage hp = JSONObject.parseObject(String.valueOf(tip.getData()), HikPage.class);
    		total = hp.getTotal();
    		list = JSON.parseArray(JSONArray.toJSONString(hp.getList()), ParkDepotInfo.class);
            for(ParkDepotInfo p : list) {
                ParkDepot parkDepot = parkDepotService.findByHikId(p.getParkCode());
                if(parkDepot != null) {
                    p.setParkDepot(parkDepot);
                }
            }
    	}
        PageInfo<ParkDepotInfo> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(total);
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(size);
        modelMap.put("pageInfo", pageInfo);
        return "manager/park-depot/list";
    }
    @RequestMapping(value="/viewParkCodes")
    public String viewParkCodes(ModelMap modelMap, String id) throws ParseException {
        Tip tip = HikUtils.getGateInfosByParkCodes(id);
        modelMap.put("data", tip.getData());
        return "manager/park-depot/codeList";
    }
    @RequestMapping(value="/viewParkCodeInfos")
    public String viewParkCodeInfos(ModelMap modelMap, String id,String parkCode) throws ParseException {
        Tip tip = HikUtils.getLaneInfosByGateCodes(id,parkCode);

        modelMap.put("data", tip.getData());
        return "manager/park-depot/laneinfos";
    }
        @RequestMapping(value="/vehicleRecords")
    @RequiresPermissions("vehicleRecords:list")
    public String vehicleRecordsList(ModelMap modelMap, Integer page, Integer size, VehicleRecord vehicleRecord, String start, String end) throws ParseException {
        Long startTime = null;
        Long endTime = null;
        if (start !=null && !start.equals("")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            startTime = sdf.parse(start).getTime();
        }
        if (end != null && !end.equals("")){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            endTime = sdf.parse(end).getTime();
        }
        Tip tip = HikUtils.getVehicleRecords(page,size,vehicleRecord.getParkCode(), vehicleRecord.getGateCode(),vehicleRecord.getPlateNo(), startTime, endTime,vehicleRecord.getCarType(),vehicleRecord.getDirect());
        HikPage hp = JSONObject.parseObject(String.valueOf(tip.getData()), HikPage.class);
        List<VehicleRecord> vehicleRecordList = JSON.parseArray(JSONArray.toJSONString(hp.getList()),VehicleRecord.class);
        PageInfo<VehicleRecord> pageInfo = new PageInfo<>(vehicleRecordList);
        Integer total = hp.getTotal();
        pageInfo.setTotal(total);
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(size);
        modelMap.put("pageInfo", pageInfo);
        return "manager/vehicleRecord/list";
    }
    @RequestMapping(value="/qrcode")
    public String qrcode(ModelMap modelMap , String laneNo, String parkCode){
        modelMap.put("laneNo", laneNo);
        modelMap.put("parkCode", parkCode);

        return "manager/park-depot/qrcode";
    }

    @RequestMapping(value = "/passPic")
    @ResponseBody
    public Tip passPic(ModelMap modelMap , String unid, String parkCode){
        Tip tip = HikUtils.getPassPicByUuid(unid, parkCode);
        return tip;
    }
    
    @RequestMapping(value = "/sendToAipark")
    @ResponseBody
    public Tip sendToAipark(String code) {
    	//查询8630平台停车场信息
		Tip tip = HikUtils.getParkingInfoByParkCode(code);
		if(tip.getSuccess() && tip.getData() != null) {
			//解析停车场数据
			ParkDepotInfo p = JSONObject.parseObject(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
			//查询是否关联本平台
			ParkDepot pd = parkDepotService.findByHikId(p.getParkCode());
			if(pd != null) {
				//操作流水号
				String num = UUIDFactory.get36Id();
				//互通平台停车场编号
				String aiparkCode = AiparkConfig.tenantCode + TimeUtils.getStringSecond(new Date());
				Map<String, String> map = new HashMap<>();
				//定义集合便于生成最后的验证签名
				map.put("accessKey", AiparkConfig.accessKey);
				map.put("parkCode", aiparkCode);
				map.put("parkName", p.getParkName());
				map.put("parkType", p.getParkType() == 1 ? "1" : "3");
				map.put("cityCode", "130304");
				map.put("address", "".equals(p.getDescription()) ? "暂无地址" : p.getDescription());
				map.put("image", "http://117.132.167.10:23108/image/3/3/322bc1512226499780984b7d613d97aa/0/22/6895/206502034/31100");
				map.put("lng", p.getParkLongitude().toString());
				map.put("lat", p.getParkLatitude().toString());
				map.put("totalSpace", p.getTotalPlot().toString());
				map.put("isFree", "1");
				map.put("rsType", "0");
				map.put("tobType", "0");
				map.put("oprNum", num);
				map.put("tenantCode", AiparkConfig.tenantCode);
				//生成签名
				String signature = SingUtils.sing(map, AiparkConfig.accessSecret);
				map.put("signature", signature);
				//汇总传输数据，字段参照互通接口文档
				NameValuePair[] data = {
						new NameValuePair("accessKey", map.get("accessKey")),
						new NameValuePair("parkCode", map.get("parkCode")),
						new NameValuePair("parkName", map.get("parkName")),
						new NameValuePair("parkType", map.get("parkType")),
						new NameValuePair("cityCode", map.get("cityCode")),
						new NameValuePair("address", map.get("address")),
						new NameValuePair("image", map.get("image")),
						new NameValuePair("lng", map.get("lng")),
						new NameValuePair("lat", map.get("lat")),
						new NameValuePair("totalSpace", map.get("totalSpace")),
						new NameValuePair("isFree", map.get("isFree")),
						new NameValuePair("rsType", map.get("rsType")),
						new NameValuePair("tobType", map.get("tobType")),
						new NameValuePair("oprNum", map.get("oprNum")),
						new NameValuePair("signature", map.get("signature")),
						new NameValuePair("tenantCode", map.get("tenantCode"))
				};
				try {
					//发送请求并得到结果
					String rs = HttpUtils.doPost(AiparkConfig.syncParkUrl, data);
					//解析返回结果
					AiparkReceive ar = JSONObject.parseObject(rs, AiparkReceive.class);
					//结果中state为0是表示成功
					if("0".equals(ar.getState())) {
						pd.setAiparkStatus(1);
						pd.setAiparkCode(aiparkCode);
						parkDepotService.updateById(pd);
						tip = new Tip(rs);
					} else {
						tip = new Tip(Integer.valueOf(ar.getState()), rs);
					}
				} catch (IOException e) {
					e.printStackTrace();
					tip = new Tip(10, "接口调用异常");
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("[" + pd.getName() + "]修改异常，此处记录上传成功的编号：" + aiparkCode);
					tip = new Tip(11, "系统异常");
				}
			} else {
				tip = new Tip(12, "请先关联此停车场");
			}
		} else {
			tip = new Tip(11, "8630平台已删除此停车场，请刷新查看");
		}
		return tip;
    }
    
    //---------------------------- property -------------------------------

    @Resource
    private ParkDepotService parkDepotService;

}
